import axios from 'axios';
import { Message, MessageBox } from 'element-ui';
import store from '../store';
import { getToken } from '@/utils/auth';

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api 的 base_url
  timeout: 10000 // 请求超时时间
});

// request拦截器
service.interceptors.request.use(
  (config) => {
    if (store.state.user.token) {
      config.headers['Authorization'] = 'Bearer ' + getToken(); // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config;
  },
  (error) => {
    // Do something with request error
    console.log('request error');
    console.log(error); // for debug
    Promise.reject(error);
  }
);

// response 拦截器
service.interceptors.response.use(
  (response) => {
    // code为非200是抛错 可结合自己业务进行修改
    // console.log(JSON.stringify(res, null, 2));
    if (response.status !== 200) {
      if (response.status === 204) {
        // 204: NoContent
        Message({
          message: '未找到相关信息，请重新输入',
          type: 'error',
          duration: 5 * 1000
        });
      } else if (response.status === 401) {
        // 401:Token 过期
        MessageBox.confirm('你已被登出，请重新登录', '确定登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/FedLogOut').then(() => {
            location.reload(); // 为了重新实例化vue-router对象 避免bug
          });
        });
      } else {
        console.log('error in response.');
        Message({
          message: response.status,
          type: 'error',
          duration: 5 * 1000
        });
      }
      return Promise.reject('error');
    } else {
      var data = response.data;
      if (data && !data.isSuccess) {
        // Message({
        //   message: data.message,
        //   type: 'error',
        //   duration: 3000
        // });
        return Promise.reject(data);
      }
      return data;
    }
  },
  (error) => {
    console.log('response error.');
    console.log(JSON.stringify(error, null, 2));
    if (error.response != null) {
      console.log('response not null');
      if (error.response.status === 404) {
        Message({
          message: '错误的请求',
          type: 'error',
          duration: 3000
        });
      }
    } else {
      console.log('response is null');
      if (error.code === 'ECONNABORTED') {
        Message({
          message: '请求超时，请稍候再试',
          type: 'error',
          duration: 3000
        });
      } else {
        Message({
          message: '网络无法连接',
          type: 'error',
          duration: 3000
        });
      }
    }

    return Promise.reject(error);
  }
);

export default service;
